package com.baidu.flutter_bmflocation;

import java.util.LinkedHashMap;

import io.flutter.embedding.engine.FlutterEngine;
import io.flutter.plugin.common.BinaryMessenger;
import io.flutter.plugin.common.MethodChannel;

public class MethodChannelManager {
    /* 声明实例对象 */
    private static MethodChannelManager sInstance;

    // 声明methodChannel
//    private MethodChannel mLocationChannel;


    private LinkedHashMap<Integer, MethodChannel> mLocationChannelStack = new LinkedHashMap<>();

    private int currentFlutterEngineHashCode;

    public void setCurrentEngine(FlutterEngine engine) {
        if (engine != null) {
            currentFlutterEngineHashCode = engine.getDartExecutor().getBinaryMessenger().hashCode();
        }
    }


    public int getCurrentFlutterEngineHashCode(){
        return currentFlutterEngineHashCode;
    }

    /* 返回实例对象 */
    public static MethodChannelManager getInstance() {
        if (null == sInstance) {
            sInstance = new MethodChannelManager();
        }
        return sInstance;
    }

    // 设置methodChannel
    public void putLocationChannel(BinaryMessenger binaryMessenger, MethodChannel methodChannel) {
        mLocationChannelStack.put(binaryMessenger.hashCode(), methodChannel);
    }

    // 获取channel
    public MethodChannel getLocationChannel() {
        MethodChannel methodChannel = mLocationChannelStack.get(currentFlutterEngineHashCode);
        if (methodChannel != null) {
            return methodChannel;
        } else {
            if (!mLocationChannelStack.isEmpty()) {
                return (MethodChannel) mLocationChannelStack.entrySet().toArray()[mLocationChannelStack.size() - 1];
            }
        }
        return null;
    }

}
